﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

/// <summary>
/// 封装Post请求方法
/// </summary>
public class HTTPHelper
{

    public HTTPHelper()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

     

    /// <summary>
    /// POST请求
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static string Post(string url,string paramData)
    {
        Stream respStream = null;
        HttpWebResponse httpResp = null;
        StreamReader respStreamReader = null;

        //StringBuilder strBuff = new StringBuilder();
        //int byteRead = 0;
        //int byteCount = 256;
        //char[] cbuffer = new char[byteCount];

       string res = null;
        try
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
            httpReq.Method = "POST";
            httpReq.ContentType = "application/x-www-form-urlencoded";
            httpReq.ContentLength = byteArray.Length;
            respStream = httpReq.GetRequestStream();
            respStream.Write(byteArray, 0, byteArray.Length);//写入参数
            respStream.Close();
            httpResp = (HttpWebResponse)httpReq.GetResponse();
            respStreamReader = new StreamReader(httpResp.GetResponseStream(), Encoding.UTF8);
             res = respStreamReader.ReadToEnd();
            //byteRead = respStreamReader.Read(cbuffer, 0, byteCount);
            //while (byteRead != 0)
            //{
            //    string strResp = new string(cbuffer, 0, byteRead);
            //    strBuff.Append(strResp);
            //    byteRead = respStreamReader.Read(cbuffer, 0, byteCount);
            //}
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
        finally
        {
            if (respStream != null)
            {
                respStream.Close();
            }

            if (httpResp != null)
            {
                httpResp.Close();
            }

            if (respStreamReader != null)
            {
                respStreamReader.Close();
            }
        }
        return res;
       // return strBuff.ToString();
    }

 
}